package bb.lanxing.device.sgdevcie.sensors;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
//import com.alipay.sdk.packet.d;
import com.umeng.socialize.net.dplus.CommonNetImpl;

import bb.lanxing.R;
import bb.lanxing.databinding.DataBindingAdapters;
import bb.lanxing.databinding.LayoutSensorHeaderHolderBinding;
import bb.lanxing.databinding.LayoutSensorListItemBinding;
import bb.lanxing.databinding.unit.SpeedUnit;
import bb.lanxing.databinding.unit.UnitConstants;
import bb.lanxing.databinding.utils.FormatterUtil;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.sprint.presenter.SearchSprintPresenter;
import bb.lanxing.lib.devices.utils.CadenceUtils;
import bb.lanxing.lib.kt.model.CadenceData;
import bb.lanxing.lib.kt.model.HeartRateData;
import bb.lanxing.lib.kt.model.PowerRateData;
import bb.lanxing.lib.kt.model.BikeTrainerData;
import bb.lanxing.lib.kt.model.IndoorBikeData;
import bb.lanxing.lib.kt.model.CrossTrainerData;
import bb.lanxing.lib.kt.model.RowerData;
import bb.lanxing.lib.kt.model.IData;
import bb.lanxing.lib.widget.SectionedRecyclerViewAdapter;
import bb.lanxing.model.database.DeviceInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import kotlin.text.StringsKt;


public final class BleSensorListAdapter extends
        SectionedRecyclerViewAdapter<SensorListHeadHolder, SensorListItemHolder, RecyclerView.ViewHolder> {
    final private static String TAG = "BleSensorListAdapter";
    private final long MAX_DATA_VALIDITY;
    private final HashMap<String, CadenceData> cadenceDataMap;
    private final HashMap<String, HeartRateData> heartRateData;
    private final HashMap<String, PowerRateData> powerRateData;
    private final HashMap<String, BikeTrainerData> bikeTrainerData;
    private final HashMap<String, IndoorBikeData> indoorBikeData;
    private final HashMap<String, CrossTrainerData> crossTrainerData;
    private final HashMap<String, RowerData> rowerData;
    private final ArrayList<BaseBleSensorViewHolder<String>> holders;
    private OnSensorClickListener onSensorClickListener;
    private SearchSprintPresenter presenter;

    public interface OnSensorClickListener {
        void onClick(SmartDevice smartDevice);
    }

    private int getRssiImgRes(int i) {
        if (i <= 25) {
            return R.drawable.ic_rssi_p100;
        }
        if (i < 51) {
            return R.drawable.ic_rssi_p75;
        }
        if (i < 76) {
            return R.drawable.ic_rssi_p50;
        }
        return R.drawable.ic_rssi_p25;
    }

    @Override
    public View getSectionHeaderView(ViewGroup viewGroup, View view, int i, int i2) {
        return null;
    }

    @Override
    public CharSequence getSectionTitle(int i) {
        return null;
    }

    @Override
    protected boolean hasFooterInSection(int i) {
        return false;
    }

    @Override
    public boolean isSectionHeaderViewType(int i) {
        return i == 1 || 2 == i;
    }

    @Override
    protected void onBindSectionFooterViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
    }

    @Override
    protected RecyclerView.ViewHolder onCreateSectionFooterViewHolder(ViewGroup viewGroup, int i) {
        return null;
    }

    public BleSensorListAdapter(SearchSprintPresenter presenter) {
        this.presenter = presenter;
        this.MAX_DATA_VALIDITY = 2000L;
        this.holders = new ArrayList<>();
        this.cadenceDataMap = new HashMap<>();
        this.heartRateData = new HashMap<>();
        this.powerRateData = new HashMap<>();
        this.bikeTrainerData = new HashMap<>();
        this.indoorBikeData = new HashMap<>();
        this.crossTrainerData = new HashMap<>();
        this.rowerData = new HashMap<>();
    }

    public final SearchSprintPresenter getPresenter() {
        return this.presenter;
    }

    public final void setPresenter(SearchSprintPresenter searchSprintPresenter) {
        this.presenter = searchSprintPresenter;
    }

    public final long getMAX_DATA_VALIDITY() {
        return this.MAX_DATA_VALIDITY;
    }

    public final ArrayList<BaseBleSensorViewHolder<String>> getHolders() {
        return this.holders;
    }

    public final OnSensorClickListener getOnSensorClickListener() {
        return this.onSensorClickListener;
    }

    public final void setOnSensorClickListener(OnSensorClickListener onSensorClickListener) {
        this.onSensorClickListener = onSensorClickListener;
    }

    public final HashMap<String, CadenceData> getCadenceDataMap() {
        return this.cadenceDataMap;
    }

    public final HashMap<String, HeartRateData> getHeartRateData() {
        return this.heartRateData;
    }

    public final HashMap<String, PowerRateData> getPowerRateData() {
        return this.powerRateData;
    }

    public final HashMap<String, BikeTrainerData> getBikeTrainerData() {
        return this.bikeTrainerData;
    }

    public final HashMap<String, IndoorBikeData> getIndoorBikeData() {
        return this.indoorBikeData;
    }

    public final HashMap<String, CrossTrainerData> getCrossTrainerData() {
        return this.crossTrainerData;
    }

    public final HashMap<String, RowerData> getRowerData() {
        return this.rowerData;
    }

    @Override
    public int getSectionCount() {
        return this.presenter.hasBoundDevice() ? 2 : 1;
    }

    @Override
    protected int getItemCountForSection(int i) {
        int deviceCount = this.presenter.getDeviceCount();
        if (!this.presenter.hasBoundDevice() || i != 0) {
            return deviceCount;
        }
        List<SmartDevice> boundDevices = this.presenter.getBoundDevices();
        if (boundDevices == null) {
            return 0;
        }
        return boundDevices.size();
    }

    @Override
    public SensorListHeadHolder onCreateSectionHeaderViewHolder(ViewGroup viewGroup, int i) {
        View inflate = LayoutInflater.from(viewGroup != null ? viewGroup.getContext() : null)
                .inflate(R.layout.layout_sensor_header_holder, viewGroup, false);
        return new SensorListHeadHolder(inflate);
    }

    @Override
    public SensorListItemHolder onCreateItemViewHolder(ViewGroup viewGroup, int i) {
        View inflate = LayoutInflater.from(viewGroup != null ? viewGroup.getContext() : null)
                .inflate(R.layout.layout_sensor_list_item, viewGroup, false);
        return new SensorListItemHolder(inflate);
    }

    @Override
    public void onBindSectionHeaderViewHolder(SensorListHeadHolder sensorListHeadHolder, int i) {
        LayoutSensorHeaderHolderBinding binding;
        int sectionHeaderViewType = getSectionHeaderViewType(i);
        if (sensorListHeadHolder == null) {
            return;
        }
        binding = sensorListHeadHolder.getBinding();
        if (binding == null) {
            return;
        }

        if (sectionHeaderViewType == 1) {
            binding.progressBar.setVisibility(View.GONE);
            binding.tvHeaderText.setText(R.string.st_my_sensors);
        } else if (sectionHeaderViewType == 2) {
            if (this.presenter.isScanning()) {
                binding.progressBar.setVisibility(View.VISIBLE);
            } else {
                binding.progressBar.setVisibility(View.GONE);
            }
            binding.tvHeaderText.setText(R.string.st_new_sensors);
        }
    }

    @Override
    public void onBindItemViewHolder(SensorListItemHolder sensorListItemHolder, int i, int i2) {
        int sectionHeaderViewType = getSectionHeaderViewType(i);
        final SmartDevice device = this.presenter.getDevice(i, i2);
        if (device == null) {
            return;
        }

        if (sensorListItemHolder == null) {
            return;
        }

        Context context = sensorListItemHolder.itemView.getContext();
        int type = device.getType();
        String name = device.getName();
        String address = device.getAddress();
        int rssi = this.presenter.getRssi(address);
        Log.d(TAG, "onBindItemViewHolder: name=" + name + ", address=" + address
                + ", rssi=" + rssi + ", device rssi=" + device.getRssi());
        int flags = device.getFlags();
        DeviceInfo deviceInfoToAddress = DeviceInfo.getDeviceInfoToAddress(address);
        String model = deviceInfoToAddress != null ? deviceInfoToAddress.getModel() : null;
        LayoutSensorListItemBinding binding = sensorListItemHolder.getBinding();
        if (binding == null) {
            return;
        }

        //add patch for iGPSPORT sensors: CAD70, SPD70
        if (flags == 7) {
            if (name.startsWith("SPD")) {
                device.setFlags(1);
            } else if (name.startsWith("CAD")) {
                device.setFlags(2);
            }
            flags = device.getFlags();
            //Log.d(TAG, "convert updated flags =" + flags);
        }

        DataBindingAdapters.setDeviceIcon(binding.ivDeviceImg, type, model);

        binding.tvDeviceName.setText(name);
        sensorListItemHolder.itemView.setOnClickListener(v -> clickBindItemViewHolder(this, device, v));
        if (sectionHeaderViewType == 1) {
            sensorListItemHolder.itemView.setOnLongClickListener(view -> {
                boolean monBindItemViewHolder;
                monBindItemViewHolder = BleSensorListAdapter
                        .onBindItemViewHolder(BleSensorListAdapter.this, device, (View) view);
                return monBindItemViewHolder;
            });
        }
        if (sectionHeaderViewType == 1) {
            binding.llConnected.setVisibility(View.VISIBLE);
            binding.llUnConnect.setVisibility(View.GONE);
            Log.d(TAG, "onBindItemViewHolder: name=" + name + ", address=" + address
                    + ", presenter isconnect=" + this.presenter.isConnected(address)
                    + ", isconnect=" + XZDeviceHelper.isConnected(address));
            if (this.presenter.isConnected(address)) {
                binding.tvDeviceState.setText(R.string.device_sprint_home_status_connected);
                binding.tvDeviceState.setTextColor(ContextCompat.getColor(context, R.color.color_gps_green_color));
            } else {
                binding.tvDeviceState.setText(R.string.st_disconnected);
                binding.tvDeviceState.setTextColor(ContextCompat.getColor(context, R.color.grey_999999));
            }
            if (type == SmartDevice.TYPE_CADENCE || type == SmartDevice.TYPE_VORTEX_CADENCE || type == SmartDevice.TYPE_CADENCE01) {
                binding.tvDeviceMode.setVisibility(View.VISIBLE);
                if (CadenceUtils.hasWheelRevolution(flags) && CadenceUtils.hasCrankRevolution(flags)) {
                    binding.tvDeviceMode.setText(R.string.device_cadence_label_wheel_and_crank);
                } else if (CadenceUtils.hasWheelRevolution(flags)) {
                    binding.tvDeviceMode.setText(R.string.device_cadence_label_wheel_mode);
                } else if (CadenceUtils.hasCrankRevolution(flags)) {
                    binding.tvDeviceMode.setText(R.string.device_cadence_label_crank_mode);
                } else {
                    binding.tvDeviceMode.setVisibility(View.GONE);
                }
            } else {
                binding.tvDeviceMode.setVisibility(View.GONE);
            }
        } else if (sectionHeaderViewType == 2) {
            binding.llUnConnect.setVisibility(View.VISIBLE);
            binding.llConnected.setVisibility(View.GONE);
            binding.tvDeviceMode.setVisibility(View.GONE);
            binding.tvDeviceDes.setVisibility(View.GONE);
            binding.tvDeviceRssi.setBackgroundResource(getRssiImgRes(Math.abs(rssi)));
        }

        String deviceAddr = device.getAddress();
        if (type == SmartDevice.TYPE_CADENCE) {
            setCadenceData(binding.tvDeviceDes, deviceAddr, flags);
        } else if (type == SmartDevice.TYPE_HEARTRATE) {
            setHeartRateData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_POWERRATE) {
            setPowerRateData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_BIKE_TRAINER) {
            setBikeTrainerData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_INDOOR_BIKE) {
            setIndoorBikeData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_CROSS_TRAINER) {
            setCrossTrainerData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_ROWER) {
            setRowerData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_HEARTRATE_BELT) {
            setHeartRateData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_VORTEX_CADENCE) {
            setCadenceData(binding.tvDeviceDes, deviceAddr, flags);
        } else if (type == SmartDevice.TYPE_HR_X2_PRO) {
            setHeartRateData(binding.tvDeviceDes, deviceAddr);
        } else if (type == SmartDevice.TYPE_CADENCE01) {
            setCadenceData(binding.tvDeviceDes, deviceAddr, flags);
        } else if (type == SmartDevice.TYPE_HEART_RATE01) {
            setHeartRateData(binding.tvDeviceDes, deviceAddr);
        }
        sensorListItemHolder.setTag(deviceAddr);
        this.holders.add(sensorListItemHolder);
    }

    public static void clickBindItemViewHolder(BleSensorListAdapter sensorAdapter, SmartDevice device, View view) {
        if (sensorAdapter.onSensorClickListener != null) {
            sensorAdapter.onSensorClickListener.onClick(device);
        }
    }

    public static boolean onBindItemViewHolder(BleSensorListAdapter sensorAdapter, SmartDevice device, View view) {
        PopupMenu popupMenu = new PopupMenu(view.getContext(), view);
        popupMenu.inflate(R.menu.device_delete);
        popupMenu.show();

        popupMenu.setOnMenuItemClickListener(menuItem -> {
            boolean monBindItemViewHolder;
            monBindItemViewHolder = onBindItemClick(sensorAdapter, device, menuItem);
            return monBindItemViewHolder;
        });
        return false;
    }

    public static boolean onBindItemClick(BleSensorListAdapter sensorAdapter, SmartDevice device, MenuItem menuItem) {
        sensorAdapter.presenter.unboundDevice(device);
        return true;
    }

    public void setCadenceData(TextView textView, String address, int i) {
        if (!this.cadenceDataMap.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        CadenceData cadenceData = this.cadenceDataMap.get(address);
        if (cadenceData == null) {
            return;
        }
        if (System.currentTimeMillis() - cadenceData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (CadenceUtils.hasWheelRevolution(i) && CadenceUtils.hasCrankRevolution(i)) {
            if (textView == null) {
                return;
            }
            int cadence = cadenceData.getCadence();
            String cadenceDisplay = cadence + " " + UnitConstants.getCadenceUnit("m");
            textView.setText(cadenceDisplay);
        } else if (CadenceUtils.hasWheelRevolution(i)) {
            SpeedUnit speedUnit = new SpeedUnit(String.valueOf(cadenceData.getSpeed() * 3.6d));
            if (textView == null) {
                return;
            }
            String speed = FormatterUtil.getNormalFormatSpeed(speedUnit.getValueBy("m"));
            String speedDisplay = speed + " " + speedUnit.getUnitString("m");
            textView.setText(speedDisplay);
        } else if (textView != null && CadenceUtils.hasCrankRevolution(i)) {
            int cadence = cadenceData.getCadence();
            String cadenceDisplay = cadence + " " + UnitConstants.getCadenceUnit("m");
            textView.setText(cadenceDisplay);
        }
    }

    public final void setHeartRateData(TextView textView, String address) {
        if (!this.heartRateData.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        HeartRateData heartRateData = this.heartRateData.get(address);
        if (heartRateData == null) {
            return;
        }
        if (System.currentTimeMillis() - heartRateData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (textView == null) {
            return;
        }
        int rate = heartRateData.getHeartRate();
        String rateDisplay = rate + " " + UnitConstants.getHeartRateUnit("m");
        textView.setText(rateDisplay);
    }


    public final void setPowerRateData(TextView textView, String address) {
        if (!this.powerRateData.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        PowerRateData powerRateData = this.powerRateData.get(address);
        if (powerRateData == null) {
            return;
        }
        if (System.currentTimeMillis() - powerRateData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (textView == null) {
            return;
        }
        int rate = powerRateData.getPowerRate();
        String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
        textView.setText(rateDisplay);
    }


    public void setBikeTrainerData(TextView textView, String address) {
        if (!this.bikeTrainerData.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        BikeTrainerData bikeTrainerData = this.bikeTrainerData.get(address);
        if (bikeTrainerData == null) {
            return;
        }
        if (System.currentTimeMillis() - bikeTrainerData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (textView == null) {
            return;
        }
        int rate = bikeTrainerData.getBikeTrainer();
        String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
        textView.setText(rateDisplay);
    }

    public void setIndoorBikeData(TextView textView, String address) {
        if (!this.indoorBikeData.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        IndoorBikeData indoorBikeData = this.indoorBikeData.get(address);
        if (indoorBikeData == null) {
            return;
        }
        if (System.currentTimeMillis() - indoorBikeData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (textView == null) {
            return;
        }
        int rate = indoorBikeData.getIndoorBike();
        String rateDisplay = rate + " " + UnitConstants.getHeartRateUnit("m");
        textView.setText(rateDisplay);
    }

    public void setCrossTrainerData(TextView textView, String address) {
        if (!this.crossTrainerData.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        CrossTrainerData crossTrainerData = this.crossTrainerData.get(address);
        if (crossTrainerData == null) {
            return;
        }
        if (System.currentTimeMillis() - crossTrainerData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (textView == null) {
            return;
        }
        int rate = crossTrainerData.getCrossTrainer();
        String rateDisplay = rate + " " + UnitConstants.getHeartRateUnit("m");
        textView.setText(rateDisplay);
    }

    public void setRowerData(TextView textView, String address) {
        if (!this.rowerData.containsKey(address)) {
            if (textView != null) {
                textView.setVisibility(View.GONE);
                return;
            }
        }
        RowerData rowerData = this.rowerData.get(address);
        if (rowerData == null) {
            return;
        }
        if (System.currentTimeMillis() - rowerData.getTimestamp() >= this.MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setVisibility(View.GONE);
            return;
        }
        if (textView != null) {
            textView.setVisibility(View.VISIBLE);
        }
        if (textView == null) {
            return;
        }
        int rate = rowerData.getRower();
        String rateDisplay = rate + " " + UnitConstants.getHeartRateUnit("m");
        textView.setText(rateDisplay);
    }


    public final BaseBleSensorViewHolder<String> getHolder(String address) {
        /*Object obj;
        Iterator<T> it = this.holders.iterator();
        while (true) {
            obj = null;
            if (!it.hasNext()) {
                break;
            }
            Object next = it.next();
            if (StringsKt.equals$default((String) ((BaseBleSensorViewHolder) next).getTag(), address, false, 2, null)) {
                obj = next;
                break;
            }
        }
        return (BaseBleSensorViewHolder) obj;*/
        BaseBleSensorViewHolder<String> baseBleSensorViewHolder;
        Iterator<BaseBleSensorViewHolder<String>> iterator = this.holders.iterator();
        while (true) {
            boolean bool = iterator.hasNext();
            baseBleSensorViewHolder = null;
            if (bool) {
                baseBleSensorViewHolder = (BaseBleSensorViewHolder<String>) iterator.next();

                if (StringsKt.equals(((BaseBleSensorViewHolder<String>) baseBleSensorViewHolder).getTag(), address, false/*, 2, null*/))
                    break;
                continue;
            }
            break;
        }
        return baseBleSensorViewHolder;
    }

    @Override
    public int getSectionHeaderViewType(int i) {
        return (!this.presenter.hasBoundDevice() || i != 0) ? 2 : 1;
    }

    public void updateValue(IData iData) {
        if (iData instanceof CadenceData) {
            this.cadenceDataMap.put(((CadenceData) iData).getDeviceAddress(), (CadenceData) iData);
            notifyDataSetChanged();
        } else if (iData instanceof HeartRateData) {
            this.heartRateData.put(((HeartRateData) iData).getDeviceAddress(), (HeartRateData) iData);
            notifyDataSetChanged();
        } else if (iData instanceof IndoorBikeData) {
            this.indoorBikeData.put(((IndoorBikeData) iData).getDeviceAddress(), (IndoorBikeData) iData);
            notifyDataSetChanged();
        } else if (iData instanceof CrossTrainerData) {
            this.crossTrainerData.put(((CrossTrainerData) iData).getDeviceAddress(), (CrossTrainerData) iData);
            notifyDataSetChanged();
        } else if (iData instanceof RowerData) {
            this.rowerData.put(((RowerData) iData).getDeviceAddress(), (RowerData) iData);
            notifyDataSetChanged();
        } else if (iData instanceof PowerRateData) {
            this.powerRateData.put(((PowerRateData) iData).getDeviceAddress(), (PowerRateData) iData);
            notifyDataSetChanged();
        }
    }
}
